const numberUtil = require('./numberUtil')

function getAverage (netValue, day, index) {
  let start = index - day + 1
  start = start < 0 ? 0 : start
  let count = 0
  for (let i = index; i >= start; i--) {
    count += netValue[i]['close']
  }
  return numberUtil.keepBtbDecimals(count / (index + 1 - start))
}

function getAverageRate (netValue, day, index) {
  let start = index - day + 1
  start = start < 0 ? 0 : start
  let count = 0
  for (let i = index; i >= start; i--) {
    count += numberUtil.countDifferenceRate(netValue[i]['high'], netValue[i]['low'])
  }
  return numberUtil.keepTwoDecimals(count / (index + 1 - start))
}

function getAverageTO (netValue, day, index) {
  let start = index - day + 1
  start = start < 0 ? 0 : start
  let count = 0
  for (let i = index; i >= start; i--) {
    if (i === index) {
      count += netValue[i]['open']
    } else {
      count += netValue[i]['close']
    }
  }
  return numberUtil.keepBtbDecimals(count / (index + 1 - start))
}

function getAverageDiff (netValue, day, index) {
  let start = index - day + 1
  start = start < 0 ? 0 : start
  let count = 0
  for (let i = index; i >= start; i--) {
    count += netValue[i]
  }
  // console.log(count)
  // console.log((index + 1 - start))
  // console.log(count)
  // console.log(count / (index + 1 - start))
  return numberUtil.keepTwoDecimals(count / (index + 1 - start))
}

module.exports = {
  getAverageList (netValue, day) {
    const list = []
    const newList = []
    netValue.forEach((item) => {
      newList.unshift(item)
    })
    newList.forEach((item, index) => {
      const average = getAverage(newList, day, index)
      list.push(average)
    })
    return list
  },
  getAverageListTO (netValue, day) {
    const list = []
    const newList = []
    netValue.forEach((item) => {
      newList.unshift(item)
    })
    newList.forEach((item, index) => {
      const average = getAverageTO(newList, day, index)
      list.push(average)
    })
    return list
  },
  getAverageRateList (netValue, day) {
    const list = []
    const newList = []
    netValue.forEach((item) => {
      newList.unshift(item)
    })
    newList.forEach((item, index) => {
      const average = getAverageRate(newList, day, index)
      list.push(average)
    })
    return list
  },
  getAverageDiffList (netValue, day) {
    const list = []
    const newList = []
    netValue.forEach((item) => {
      newList.push(item)
    })
    newList.forEach((item, index) => {
      const average = getAverageDiff(newList, day, index)
      list.push(average)
    })
    return list
  }
}
